﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static KongMing.ORM.SqlSugar.SqlSugarHelper;
using SqlSugar;
using KongMing.ORM.SqlSugar.Models;
using System.Linq.Expressions;

namespace KongMing.ORM.SqlSugar.DynamicExpression
{
    public class 解析表达式
    {
        public static void Go()
        {
            using (var db = GetDB())
            {
                //解析表达式
                //1.声明 ExpressionContext 表达式解析器，(不同数据库这个类型不同)
                var sqlServerExpContext = GetExpContextByDbType(db.CurrentConnectionConfig.DbType);
                //2.创建表达式
                Expression<Func<Book, bool>> exp = x => (x.Title.Contains("三体") || x.Title == "西游记") && x.IsDelete == 0;
                //3.Resolve方法绑定表达式，指定表达式语句的类型
                sqlServerExpContext.Resolve(exp, ResolveExpressType.WhereSingle);
                //4.获取转换后的sql语句
                var whereSql = sqlServerExpContext.Result.GetString();
                //5.获取参数集合
                var pars = sqlServerExpContext.Parameters;

                var books = db.Queryable<Book>().Where(whereSql).AddParameters(pars).ToList();
            }
        }

        /// <summary>
        /// 创建表达式解析器
        /// </summary>
        /// <param name="dbType">当前连接的数据库类型</param>
        public static ExpressionContext GetExpContextByDbType(DbType dbType)
        {
            ExpressionContext expContext = dbType switch
            {
                DbType.MySql => new MySqlExpressionContext(),
                DbType.SqlServer => new SqlServerExpressionContext(),
                DbType.Sqlite => new SqliteExpressionContext(),
                DbType.Oracle => new OracleExpressionContext(),
                DbType.PostgreSQL => new PostgreSQLExpressionContext(),
                DbType.Dm => new DmExpressionContext(),
                DbType.Kdbndp => new KdbndpExpressionContext(),
                _ => throw new Exception("DbType不支持")
            };
            return expContext;
        }
    }
}
